"""
Flask应用工厂函数
初始化Flask应用、数据库、登录管理等扩展
"""
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
from flask_cors import CORS
from flask_wtf.csrf import CSRFProtect
from config import config

# 初始化扩展
db = SQLAlchemy()
login_manager = LoginManager()
csrf = CSRFProtect()

def create_app(config_name='default'):
    """
    应用工厂函数
    
    Args:
        config_name: 配置名称 ('development', 'production', 'testing')
    
    Returns:
        Flask应用实例
    """
    app = Flask(__name__)
    
    # 加载配置
    app.config.from_object(config[config_name])
    
    # 初始化扩展
    db.init_app(app)
    login_manager.init_app(app)
    csrf.init_app(app)
    CORS(app)
    
    # 配置登录管理器
    login_manager.login_view = 'auth.login'
    login_manager.login_message = '请先登录以访问此页面。'
    login_manager.login_message_category = 'info'
    
    # 注册蓝图
    from app.main import bp as main_bp
    app.register_blueprint(main_bp)
    
    from app.auth import bp as auth_bp
    app.register_blueprint(auth_bp, url_prefix='/auth')
    
    from app.api import bp as api_bp
    app.register_blueprint(api_bp, url_prefix='/api')
    
    from app.admin import bp as admin_bp
    app.register_blueprint(admin_bp, url_prefix='/admin')
    
    # 创建数据库表
    with app.app_context():
        db.create_all()
        
        # 创建默认管理员账号
        from app.models import User
        admin = User.query.filter_by(username=app.config['DEFAULT_ADMIN_USERNAME']).first()
        if not admin:
            admin = User(
                username=app.config['DEFAULT_ADMIN_USERNAME'],
                email=app.config['DEFAULT_ADMIN_EMAIL'],
                role='admin'
            )
            admin.set_password(app.config['DEFAULT_ADMIN_PASSWORD'])
            db.session.add(admin)
            db.session.commit()
            print(f"默认管理员账号已创建: {app.config['DEFAULT_ADMIN_USERNAME']}")
        
        # 创建默认教师账号
        teacher = User.query.filter_by(username='teacher').first()
        if not teacher:
            teacher = User(
                username='teacher',
                email='teacher@wxxx.com',
                role='admin',
                real_name='教师用户'
            )
            teacher.set_password('123456')
            db.session.add(teacher)
            db.session.commit()
            print("默认教师账号已创建: teacher")
        
        # 创建默认测试账号
        test_user = User.query.filter_by(username='test').first()
        if not test_user:
            test_user = User(
                username='test',
                email='test@wxxx.com',
                role='student',
                real_name='测试用户'
            )
            test_user.set_password('123456')
            db.session.add(test_user)
            db.session.commit()
            print("默认测试账号已创建: test")
    
    return app

@login_manager.user_loader
def load_user(user_id):
    """
    用户加载回调函数
    
    Args:
        user_id: 用户ID
    
    Returns:
        用户对象或None
    """
    from app.models import User
    return User.query.get(int(user_id))